# -*- encoding: utf-8 -*-

"""
@File:      container.py
@Time:      2023/08/22 16:18:47
@Author:    liangjian
@Version:   1.0
@License:   Mulan PSL v2

"""
import time
from enum import Enum
from common.hosts import LocalHost, RemoteHost
from common.sysinfo import SysInfo
from common.os_env import OSType, Env, Image
import os
class Container(SysInfo):
    """
    Create and destroy containers
    """

    def cmd(self, command, host="remote", ignore_status=False):
        if host == 'remote':
            return self.remote.cmd(command, ignore_status=ignore_status)
        elif host == 'local':
            return self.local.cmd(command, ignore_status=ignore_status)

    def create_container(self,container_engine,image,version,container_id):
        http_str=""
        if os.environ.get('TONE_OSS_PROXY_HOST') is not None:
            http_str = "-e http_proxy={0} -e https_proxy={0}".format(os.environ.get('TONE_OSS_PROXY_HOST'))
        if container_engine == 'docker':
            ret_c,ret_o = self.cmd(" rpm -qa  | grep podman ",ignore_status=True)
            if ret_c == 0:
                self.cmd('yum remove podman -y')
            if image.ostype == OSType.ANOLIS:
                self.cmd('yum install -y yum-utils')
                if image.ostype == OSType.ANOLIS and image.version.startswith('23'):
                    self.cmd('yum install docker -y --enablerepo=os')
                else:
                    self.cmd('yum install docker -y --enablerepo=Plus')
            elif image.ostype == OSType.CENTOS or image.ostype == OSType.ALINUX:
                self.cmd('yum install -y yum-utils')
                self.cmd('yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo')
                self.cmd('yum install docker-ce -y')
            elif image.ostype == OSType.FEDORA:
                self.cmd('dnf -y install dnf-plugins-core')
                self.cmd('dnf config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/fedora/docker-ce.repo')
                self.cmd('dnf update -y')
                self.cmd('dnf install docker-ce -y')
            elif image.ostype == OSType.OPENSUSE_LEAP:
                self.cmd('zypper install -y docker')
            elif image.ostype == OSType.UBUNTU:
                if image.version == '18.04':
                    self.cmd('apt-get update -y')
                    self.cmd('apt-get -y install software-properties-common 1>/dev/null',ignore_status=True)
                self.cmd('curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -')
                self.cmd('add-apt-repository "deb [arch=$(dpkg --print-architecture)] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"')
                self.cmd('apt-get update -y')
                if image.arch == 'aarch64':
                    self.cmd('rm -rf /etc/grub.d/10_linux*')
                    self.cmd('rm -rf /var/lib/dpkg/updates/*')
                self.cmd('DEBIAN_FRONTEND=noninteractive apt-get -y install docker-ce --no-install-recommends 1>/dev/null',ignore_status=True)
                ret_c,output = self.cmd('service docker start',ignore_status=True)
                if 'docker.service is masked' in output:
                    self.cmd('systemctl unmask docker.service && systemctl unmask docker.socket')
                    self.cmd('systemctl start containerd.service')
            elif image.ostype == OSType.DEBIAN:
                self.cmd('apt-get update -y')
                self.cmd('apt-get install apt-transport-https ca-certificates curl gnupg software-properties-common -y 1>/dev/null')
                self.cmd('curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -')
                self.cmd('add-apt-repository "deb [arch=$(dpkg --print-architecture)] https://download.docker.com/linux/debian $(lsb_release -cs) stable"')
                self.cmd('apt-get update -y')
                self.cmd('apt-get -y install docker-ce 1>/dev/null',ignore_status=True)
                self.cmd('cat /etc/containers/registries.conf | grep docker.io',ignore_status=True)
            else:
                self.log.debug("docker install: this operating system does not require testing")
            
            ret_c,containerd_status = self.cmd('systemctl is-active containerd.service',ignore_status=True)
            if containerd_status != 'active':
                self.cmd('systemctl start containerd.service')
            for i in range(30):
                ret_c,docker_status = self.cmd('systemctl is-active '+container_engine,ignore_status=True)
                if docker_status != 'active':
                    time.sleep(20)
                    self.cmd('systemctl reset-failed '+container_engine,ignore_status=True)
                    self.cmd('systemctl start '+container_engine,ignore_status=True)
                else:
                    break
        elif container_engine == 'podman':
            ret_c,ret_o = self.cmd("rpm -qa | grep docker",ignore_status=True)
            if ret_c == 0:
                self.cmd('yum remove docker* -y')
            self.cmd('yum install -y yum-utils')
            self.cmd('yum install podman -y')    
        if 'tar' in version:
            self.cmd('wget '+version+' 1>/dev/null 2>&1', ignore_status=True)
            self.cmd(container_engine+' import '+version.split('/')[-1]+' anolis:23')
            ret_c,image_exist = self.cmd(container_engine+' image ls')
            self.assertTrue('anolis' in image_exist,"import image failed")
            ret_c,container_id = self.cmd(container_engine+' run -dit --privileged=true -v /home:/home anolis:23 bash')
        else:
            http_proxy = os.environ.get('TONE_OSS_PROXY_HOST')
            if http_proxy is not None and container_engine == "docker":
                file_path = '/etc/systemd/system/docker.service.d/http-proxy.conf'
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
                with open(file_path, 'w') as f:
                    f.write('[Service]\n')
                    f.write(f'Environment="HTTP_PROXY={http_proxy}"\n')
                    f.write(f'Environment="HTTPS_PROXY={http_proxy}"\n')
                    f.write('Environment="NO_PROXY=localhost,127.0.0.1"\n')
                self.cmd("systemctl daemon-reload")
                self.cmd("systemctl restart docker")
            self.cmd(container_engine+' pull '+version)
            ret_c,output1 = self.cmd(container_engine+' image ls')
            print("output1:%s" % output1)
            if ':' in version:
                self.image_name = version.split(':')[0]
            else:
                self.image_name = version
            self.assertTrue(self.image_name in output1,"pull image failed")
            if 'anolis' or 'alinux' not in self.image_name.split('/')[-1]:
                ret_c1,container_id = self.cmd(container_engine+' run '+http_str+ ' -dit --privileged=true -v /home:/home '+version,ignore_status=True)
                command = container_engine +' exec '+container_id+' '+' echo "$LANG" '
                ret_c2,lang_ret = self.cmd(command,ignore_status=True)
                if ret_c1 != 0 or ret_c2 != 0:
                    ret_c,container_id = self.cmd(container_engine+' run '+http_str+ ' -dit --privileged=true '+version+' bash')
            else:
                ret_c,container_id = self.cmd(container_engine+' run '+http_str+ ' -dit --privileged=true -v /home:/home '+version+' /usr/sbin/init')
        ret_c,container_status = self.cmd(container_engine+' ps -a | grep Up -wo')
        self.assertTrue('Up' in container_status,"run image failed") 
        return container_id
        
    def destroy_container(self,container_engine,container_id,version,image):
        if container_id:
            self.cmd(container_engine+' stop '+container_id+' && '+container_engine+' container prune -f')
            if 'tar' in version:
                self.cmd(container_engine+' image rm anolis:23')
            else:
                self.cmd(container_engine+' rmi '+version)
        self.cmd(container_engine+' container prune -f')
        if image.ostype == OSType.ANOLIS:
            self.cmd('yum remove -y '+container_engine)
        elif image.ostype == OSType.CENTOS or image.ostype == OSType.ALINUX:
            if 'docker' == container_engine:
                self.cmd('yum remove -y docker-ce')
            elif 'podman' == container_engine:
                self.cmd('yum remove -y '+container_engine)
        elif image.ostype == OSType.FEDORA:
            if 'docker' == container_engine:
                self.cmd('dnf remove -y docker-ce')
            elif 'podman' == container_engine:
                self.cmd('dnf remove -y '+container_engine)
        elif image.ostype == OSType.OPENSUSE_LEAP:
            self.cmd('zypper remove -y '+container_engine)
        elif image.ostype == OSType.UBUNTU or image.ostype == OSType.DEBIAN:
            if 'docker' == container_engine:
                self.cmd('apt-get -y remove docker-ce')
            elif 'podman' == container_engine:
                self.cmd('apt-get -y remove '+container_engine)
